import { GetGiga2bProductInfoMessage } from '@/config';
import { request } from './request';

// 获取产品页面文档字符串
export async function getProductDocumentHTML<T = string>(gigaProductId: string) {
  return request<T, T>({
    url: `https://www.gigab2b.com/index.php`,
    method: 'GET',
    params: {
      route: 'product/product',
      product_id: gigaProductId,
    },
  });
}

// 以硬编码的方式获取对应的产品信息
export interface GetProductBaseInfoResult {
  // 200 表示成功
  code: number;
  msg: string;
  data: {
    product_info: {
      sku: string;
      product_name: string;
      product_type: number;
      category_info: Array<{
        id: number;
        category_level: string;
        name: string;
      }>;
      original_info: {
        is_show_original: boolean;
        original_design_images: string[]; // 假设原始设计图片是字符串URL数组
        original_product_image_url: string;
      };
      combo_flag: boolean;
      tags_info: string[];
      first_available_date: string;
      non_sellable_on_full_list: Array<{
        platform_name: string;
        effective_time: string;
        milliseconds: number;
        status: number;
        action: string;
      }>; // 根据数据为空数组，具体类型需根据业务补充
      return_rate: {
        return_rate: number;
        return_rate_str: string;
        purchase_num: number;
      };
      download_count: number;
      main_image: {
        popup: string;
        thumb: string;
      };
      image_list: Array<{
        popup: string;
        thumb: string;
      }>;
      product_video: any[]; // 根据数据为空数组，具体类型需根据业务补充
      white_labeling_flag: number;
      brand_name: string | null;
      specification: {
        sku: string;
        upc: string;
        origin_place: string;
        product_name: string;
        information_custom_field: any[]; // 根据数据为空数组，具体类型需补充
        danger_info: any | null; // 根据数据为null，具体类型需补充
        is_customize: boolean;
        product_type_name: string;
        product_dimensions: {
          assemble_info: {
            length_show: string;
            width_show: string;
            height_show: string;
            weight_show: string;
          };
          dimensions_custom_field: any[]; // 根据数据为空数组，具体类型需补充
          unit_length: string;
          unit_weight: string;
        };
        package_size: {
          unit_length: string;
          unit_weight: string;
          general:
            | {
                height: string;
                irregular_content: string | null;
                is_irregular_product: boolean;
                length: string;
                weight: string;
                width: string;
              }
            | [];
          simple: {
            height: string;
            irregular_content: string | null;
            is_irregular_product: boolean;
            length: string;
            weight: string;
            width: string;
          };
          combo: Array<{
            length: string;
            width: string;
            height: string;
            weight: string;
            product_id: number;
            qty: number;
            sku: string;
            is_irregular_product: boolean;
            irregular_content: any | null;
          }>;
          simple_unit_length: string;
          simple_unit_weight: string;
          package_type_information_info: {
            title: string;
            is_link: number;
            url: string;
            information_id: number;
            site_id: number;
          };
        };
        property_infos: Array<{
          property_name: string;
          property_value_name: string;
        }>;
        white_labeling_zip_download_url: string;
      };
      description: string; // HTML内容保持为字符串
      characteristic: string; // HTML内容保持为字符串
      documents: {
        certification_documents: any[]; // 根据数据为空数组，具体类型需补充
        material_document: any[]; // 根据数据为空数组，具体类型需补充
        material_video: any[]; // 根据数据为空数组，具体类型需补充
      };
      return_warranty_text: string; // HTML内容保持为字符串
      marketplace_policy: string; // HTML内容保持为字符串
      internation_fulfillment_fee: {
        can_internation: number;
        list: any[]; // 根据数据为空数组，具体类型需补充
        msg: string;
      };
      additional_information: {
        logistics_information: any[]; // 根据数据为空数组，具体类型需补充
        cooperate_images: any[]; // 根据数据为空数组，具体类型需补充
        cooperate_transactions: any[]; // 根据数据为空数组，具体类型需补充
        cooperate_remark: string;
        brand_information: any | null;
      };
      protection_service_rate: Array<{
        title: string;
        service_rate_show: string;
        config_type: number;
        config_sub_type: number;
      }>;
      is_product_available: boolean;
      is_canada_product: boolean;
      show_horn_new: boolean;
      is_seller_self: boolean;
      can_contact_mail: boolean;
      ltl_info: {
        is_ltl: boolean;
      };
      no_login_and_unavaiable: boolean;
      is_connected: boolean;
      is_japan_duty_free: boolean;
    };
    seller_info: {
      seller_id: number;
      store_name: string;
      store_code: string;
      store_logo: string;
      decoration_is_show: boolean;
      decoration_url: string;
      decoration_jump_link: string;
      giga_index_info: {
        score: string;
        comprehensive: any[]; // 根据数据为空数组，具体类型需补充
        percentile_rank: number;
        score_task_number: string;
        is_new_seller: boolean;
        deduction_score_list: any[]; // 根据数据为空数组，具体类型需补充
        giga_index_information_id: string;
      };
      performance: Array<{
        name: string;
        icon: string;
        value: number | string; // 根据数据混合类型
        value_show: string;
        na_tip: string;
        color: string;
      }>;
      performance_giga_onsite: any | null; // 根据数据为null，具体类型需补充
      is_giga_onsite: boolean;
      is_designates_giga_warehouse_seller: boolean;
      is_charge_cloud_fee_seller: boolean;
      seller_status: boolean;
      not_support_stock: boolean;
      is_notice_onsite_transaction: boolean;
      is_show_seller_info: boolean;
    };
    other_info: {
      is_collected: boolean;
      is_manage_preview: boolean;
      is_in_my_wishlist: boolean;
      contact_seller_url: string;
      giga_index_url: string;
      is_support_credit: number;
    };
  };
}
export async function getProductBaseInfo<T = GetProductBaseInfoResult>(id: string) {
  return request<T, T>({
    url: `https://www.gigab2b.com/index.php`,
    method: 'GET',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: {
      route: '/product/info/info/baseInfos',
      product_id: id,
    },
  });
}

// 以硬编码的方式获取对应的产品价钱和库存信息
interface LinkInfo {
  title: string;
  is_link: number;
  url: string;
  information_id: number;
  site_id: number;
}
export interface GetProductPriceInfoResult {
  // 200 表示成功
  code: number;
  msg: string;
  data: {
    price_visible: boolean;
    qty_visible: boolean;
    is_seller_self: boolean;
    is_connected: boolean;
    is_cooperate: boolean;
    is_sales_represent: boolean;
    is_in_rebate: boolean;
    my_stock: any | null;
    base_price_info: {
      price: number;
      line_through_price: number;
      is_delicacy: boolean;
      text_custom_or_price: string;
      change_price_info: {
        is_advance: boolean;
        effect_date: string | null;
        effect_seconds: number;
        up_price: number | null;
      };
      can_bid: boolean;
      map_price: number | null;
      srp_price: number | null;
      line_through_normal_price: number | null;
    };
    complex_transaction_list: {
      margin: {
        can_bid: boolean;
        payment_ratio: string;
        link_info: LinkInfo;
        list: {
          id: number;
          contract_id: number;
          template_id: string;
          min_quantity: number;
          max_quantity: number;
          price: number;
          days: number;
          payment_ratio: string;
          show_price: string;
        }[];
      };
    };
    activity_promotion_list: any[];
    option: {
      product_id: number;
      is_selected: boolean;
      carousel_images: {
        popup: string;
        thumb: string;
      }[];
      title: string;
      is_have_available_stock: boolean;
    }[];
    stock_distributions: any | null;
    quantity: {
      quantity: number;
      show_more_on_the_way: boolean;
      more_on_the_way_info: any | null;
      stock_tip_html: string;
    };
    discount_info: any | null;
    fulfillment_options: {
      can_show: boolean;
      has_cwf: boolean;
      has_ltl: boolean;
      is_combo: boolean;
      ship_remark: string;
      amazon_help_link_url: LinkInfo;
      drop_ship: {
        shipping_fee_show: string;
        package_fee_show: string;
        total_amount: number;
        total_show: string;
        link_info: LinkInfo;
        estimated_ship_day_show: boolean;
        estimated_ship_day: {
          min_day: number;
          max_day: number;
        };
        handling_time_show: boolean;
        handling_time: {
          min_day: number;
          max_day: number;
        };
        is_support_amazon_drop_ship: boolean;
        amazon_shipping_fee_show: string | null;
        amazon_total_amount: number | null;
        amazon_total_show: string | null;
      };
      cloud: {
        shipping_fee_show: string;
        package_fee_show: string;
        overweight_surcharge_show: string;
        overweight_surcharge_tip: string;
        min_total_amount: number;
        max_total_amount: number;
        total_show: string;
        information_url: string;
        estimated_ship_day_show: boolean;
        estimated_ship_day: {
          min_day: number;
          max_day: number;
        };
        handling_time_show: boolean;
        handling_time: {
          min_day: number;
          max_day: number;
        };
        link_info: LinkInfo;
        cwf_config: {
          cwf_freight_config: {
            order_limit_volume: number;
            cwf_sku_limit_volume: string;
            cwf_freight_mode: {
              id: number;
              mode_version: number;
              country_id: number;
              base_fee: string;
              param: string;
              max_weight: number;
            }[];
            product_freight_coefficient: any[];
          };
          product_freight_coefficient: number;
          weight: number;
          package_fee: number;
        };
        weight_volume_info: {
          weight: {
            unit: string;
            weight_total: number;
            weight_list: {
              weight: number;
              qty: number;
            }[];
          };
          volume: {
            unit: string;
            volume_total: number;
            volume_list: {
              length_inch: number;
              width_inch: number;
              height_inch: number;
              qty: number;
            }[];
          };
        };
      };
    };
    storage_fee_info: {
      storage_fee_day: string;
      link_info: LinkInfo;
      storage_information_url: string;
    };
    warehouse_link_info: {
      title: string;
      is_link: number;
      url: string;
      information_id: number | null;
      site_id: number;
    };
    canada_tax_description_link_info: {
      title: string;
      is_link: number;
      url: string;
      information_id: number | null;
      site_id: number;
    };
  };
}
export async function getProductPriceInfo<T = GetProductPriceInfoResult>(id: string) {
  return request<T, T>({
    url: `https://www.gigab2b.com/index.php`,
    method: 'GET',
    params: {
      route: '/product/info/price/list',
      product_id: id,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
}

// 登录到 gigab2b
export interface LoginResult {
  code: number;
  msg: string;
  data: {
    attribute: string;
  };
}
export async function login<T = LoginResult>(email: string, password: string) {
  const loginUrl = 'https://www.gigab2b.com/index.php?route=/account/login';
  return request<T, T>({
    url: loginUrl,
    method: 'POST',
    headers: {},
    data: {
      email,
      password,
    },
  });
}

// 获取登录的文档对象
export interface GetLoginDocumentOption {
  acw_sc__v2: string;
}
export async function getLoginDocument<T = Document>({ acw_sc__v2 }: GetLoginDocumentOption) {
  const loginUrl = 'https://www.gigab2b.com/index.php?route=account/login';
  return request<T, T>({
    url: loginUrl,
    method: 'GET',
    headers: {
      // Referer: 'https://www.gigab2b.com/index.php?route=account/login',
    },
    responseType: 'document',
  });
}

// 获取 giga 的 accessToken
export interface GetAccessTokenResult {
  access_token: string;
  token_type: string;
  expires_in: number;
  scope: string;
  addtional_info: {
    customerId: number;
  };
  jti: string;
}

export async function getAccessToken<T = GetAccessTokenResult>(
  clientId: string,
  clientSecret: string,
) {
  return request<T, T>({
    url: 'https://api.gigacloudlogistics.com/api-auth-v1/oauth/token',
    method: 'POST',
    data: {
      grant_type: 'client_credentials',
      client_id: clientId,
      client_secret: clientSecret,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
}

// 获取 giga 中相应的 sku 对应的产品详情
export interface GetGigaProductInfoResult {
  code: number;
  msg: string;
  data: {
    product_info: {
      product_id: string;
      product_name: string;
      product_code: string;
      product_image: string;
      product_image_list: string[];
      product_price: string;
      product_price_list: string[];
      product_price_unit: string;
    };
  };
}

export interface GetGigaProductInfoOptions {
  sku: string;
  accessToken: string;
  tokenType: string;
}

// 使用限制 20 times in 10 seconds
export async function getGigaProductInfo<T = GetGigaProductInfoResult>({
  sku,
  accessToken,
  tokenType,
}: GetGigaProductInfoOptions) {
  return request<T, T>({
    url: 'https://api.gigacloudlogistics.com/api-b2b-v1/product/detailInfo',
    method: 'POST',
    data: {
      skus: [sku],
    },
    headers: {
      Authorization: `${tokenType} ${accessToken}`,
    },
  });
}

// 下载资源前刷新权限
export interface GetGigaResourcePermissionResult {
  // 200 表示成功
  code: number;
  msg: string;
}
export async function getGigaResourcePermission<T = GetGigaResourcePermissionResult>({
  gigaProductId,
  customerId,
  xCsrfToken,
}: {
  gigaProductId: string;
  customerId: number;
  xCsrfToken: string;
}) {
  return request<T, T>({
    url: 'https://www.gigab2b.com/index.php',
    method: 'POST',
    params: {
      route: '/product/product/download',
    },
    headers: {
      'x-csrf-token': xCsrfToken,
    },
    data: {
      product_id: gigaProductId,
      customer_id: customerId,
      product_type: 1,
    },
  });
}

// 下载资源
export async function downloadGigaResource(gigaProductId: string) {
  return request<Blob, Blob>({
    url: 'https://www.gigab2b.com/index.php',
    method: 'GET',
    params: {
      route: 'product/product/downloadZip',
      product_id: gigaProductId,
    },
    responseType: 'blob',
    headers: {
      'Content-Type': '',
    },
  });
}

// 分页搜索对应的产品 id
interface SearchProductIdsResult {
  code: number;
  msg: string;
  data: {
    category: Array<{
      category_id: number;
      parent_id: number;
      category_name: string;
      country_id: number;
      children: Array<{
        category_id: number;
        parent_id: number;
        category_name: string;
        country_id: number;
        children: Array<{
          category_id: number;
          parent_id: number;
          category_name: string;
          country_id: number;
          children: any[]; // 根据实际情况调整类型
        }>;
      }>;
    }>;
    setting: any[]; // 根据实际情况调整类型
    setting_property: Array<{
      label: string;
      is_collapse: boolean;
      is_item_collapse: boolean;
      items: Array<{
        label: string;
        value: number;
        count: string;
        matomo: string;
      }>;
    }>;
    store_list: any[]; // 根据实际情况调整类型
    product_list: number[];
    sponsored_product_list: any[]; // 根据实际情况调整类型
    search_info: {
      request_id: string;
      keyword: string;
      total_seller: number;
      is_backend_setting: number;
      max_size: number;
    };
    pagination: {
      total: number;
    };
    left_filter_guide_show: boolean;
    grid_type_guide_show: boolean;
  };
}

export async function searchProductIds<T = SearchProductIdsResult>(
  SearchProductIdsOptions: Record<string, any>,
) {
  return request<T, T>({
    url: 'https://www.gigab2b.com/index.php?route=/product/list/search',
    method: 'POST',
    data: SearchProductIdsOptions,
    params: {
      route: '/product/list/search',
    },
  });
}

// 根据多个产品的 id 获取多个产品的详细信息

export interface GetProductInfosByIdsResult {
  code: number;
  msg: string;
  data: Array<{
    product: {
      id: number;
      name: string;
      image: string;
      sku: string;
      brand_name: string | null;
      is_available: boolean;
      tags: string[];
      is_original_design: boolean;
      show_white_labeling: boolean;
      retail_ready_flag: boolean;
      complex_transactions: string[];
      price_info: {
        min: number;
        max: number;
        map: number | null;
        delete_price_show: string;
      };
      quantity_info: {
        qty_str: string;
      };
      fulfillment_info: {
        min: number;
        max: number;
      };
      more_on_the_way_info: any | null; // 根据实际情况调整类型
      discount_tip: string;
      is_show_image_icon: boolean;
      is_show_video_icon: boolean;
      estimated_qty: string;
      date_of_next_arrival: string;
      is_japan_duty_free: boolean;
    };
    seller: {
      seller_id: number;
      store_name: string;
      store_code: string;
      is_giga_onsite: boolean;
      giga_index_info: {
        score: string;
        percentile_rank: string;
        is_new_seller: boolean;
        giga_index_information_id: string;
      };
      performance: Array<{
        type: string;
        value: string;
      }>;
    };
    other: {
      is_connected: boolean;
      is_in_my_wishlist: boolean;
      seller_id: number;
      is_seller_self: boolean;
    };
  }>;
}
export async function getProductInfosByIds<T = GetProductInfosByIdsResult>(
  productIds: (number | string)[],
) {
  return request<T, T>({
    url: 'https://www.gigab2b.com/index.php',
    method: 'POST',
    params: {
      route: '/product/list/list',
    },
    data: {
      product_ids: productIds,
      with_seller: true,
      with_wishlist: true,
      type: 'grid',
    },
  });
}
